package com.soul.doc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.soul.common.exception.BaseException;
import com.soul.common.utils.ListUtil;
import com.soul.doc.bean.dto.CollectionDto;
import com.soul.doc.bean.po.LoveMusicPo;
import com.soul.doc.mapper.LoveMusicMapper;
import com.soul.doc.service.LoveMusicService;
import com.soul.common.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户喜欢歌曲 服务实现类
 * </p>
 *
 * @author sws
 * @since 2023-12-06 16:32:35
 */
@Service
public class LoveMusicServiceImpl extends BaseService<LoveMusicMapper, LoveMusicPo> implements LoveMusicService {

    @Override
    public boolean addLoveMusic(CollectionDto collectionDto){
        if (!StpUtil.isLogin()){
            throw new BaseException("未登录");
        }
        long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 100L;
        List<LoveMusicPo> list = this.getLambadaQueryWrapper().eq(LoveMusicPo::getUserId, userId).list();
        List<Long> musicIds = ListUtil.toValueList(list, LoveMusicPo::getMusicId);
        if (ObjectUtil.isNotEmpty(musicIds) && musicIds.contains(collectionDto.getMusicId())){
            if (ObjectUtil.equals(collectionDto.getType(),"remove")){
                // 取消收藏
                this.lambdaUpdate()
                        .eq(LoveMusicPo::getUserId, userId)
                        .eq(LoveMusicPo::getMusicId, collectionDto.getMusicId())
                        .remove();
                return true;
            }
            return false;
        }
        LoveMusicPo loveMusicPo = new LoveMusicPo();
        loveMusicPo.setMusicId(collectionDto.getMusicId())
                .setUserId(userId);
        Long maxSort = this.getMaxSort(LoveMusicPo::getUserId, userId);
        loveMusicPo.setSort(maxSort);
        this.save(loveMusicPo);
        return true;
    }

    @Override
    public List<LoveMusicPo> getLoveMusic(){
        if (!StpUtil.isLogin()){
            throw new BaseException("未登录");
        }
        long userId = StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 100L;
        return this.getLambadaQueryWrapper().eq(LoveMusicPo::getUserId, userId).orderByDesc(LoveMusicPo::getSort).list();
    }

    @Override
    public List<Long> getLoveMusicIds(){
        List<LoveMusicPo> loveMusic = this.getLoveMusic();
        return ListUtil.toValueList(loveMusic, LoveMusicPo::getMusicId);
    }
}
